package com.webapp.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.webapp.model.Application;
import com.webapp.model.ViewTableModel;

/**
 * Servlet implementation class SearchSortFilterServlet.
 * Used to apply filtering to application table.
 */
public class SearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchServlet() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		//final Logger fLogger = Logger.getLogger(getClass().getPackage().getName());
		
		// Retrieve session.
		HttpSession session = request.getSession();
		
		// Retrieve search attribute.
		String searchKeyword = (String)request.getParameter("search");
		
		//fLogger.log(Level.INFO, "Attempting to search with: " + searchKeyword);
		
		// Retrieve filtered list.
		ArrayList<Application> filteredList = ViewTableModel.search(searchKeyword);
	
		if (filteredList != null)
		{
			if (!filteredList.isEmpty())
			{
				// Set it as new table.
				session.setAttribute("Table", filteredList);
				
				// Retrieve dispatcher.
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/viewApps.jsp");
				
				//fLogger.log(Level.INFO, "Search is sucessful.");
				// Forward request.
				dispatcher.forward(request, response);
				
				//fLogger.log(Level.INFO, "Intializing filtered table.");
			} else {
				// Restore original table.
				session.setAttribute("Table", ViewTableModel.getTable());
				
				//fLogger.log(Level.INFO, "Search for: " + searchKeyword + " is unsucessful.");
				// Sent back a response that search returned empty results.
				response.sendRedirect("viewApps.jsp?edit=empty_search");
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{}

}
